/**
 * 通用图弹出对话框
 * @param params
 */
function crud_dlg(params) {

    if (params.title == undefined) {
        params.title = "弹出框";
    }

    if (params.width == undefined) {
        params.width = $(window).width() - 50;
    } else {
        if ($(window).width() <= params.width) {
            params.width = $(window).width() - 50;
        }
    }

    if (params.height == undefined) {
        params.height = $(window).height() - 50;
    } else {
        if ($(window).height() <= params.height) {
            params.height = $(window).height() - 50;
        }
    }

    if (params.iconCls == undefined) {
        params.iconCls = 'fa fa-easyui fa-location-arrow fa-fw';
    }

    if (params.closed == undefined) {
        params.closed = false;
    }

    if (params.cache == undefined) {
        params.cache = false;
    }

    if (params.modal == undefined) {
        params.modal = false;
    }

    if (params.maximizable == undefined) {
        params.maximizable = false;
    }

    if (params.resizable == undefined) {
        params.resizable = true;
    }

    if (params.isParent == undefined) {
        params.isParent = false;
    }

    if (params.top == undefined) {
        params.top = "50px";
    }

    if (params.dlgId === undefined) {
        params.dlgId = 'crud_dlg';
    }

    if (params.buttons === undefined) {
        params.buttons = null;
    }

    var element = $('<div></div>');
    element.attr('id', params.dlgId);

    if (params.isParent) {
        element.appendTo(parent.document.body);
    } else {
        element.appendTo(document.body);
    }

    element.dialog({
        title: params.title,
        width: params.width,
        height: params.height,
        iconCls: params.iconCls,
        maximizable: params.maximizable,
        resizable: params.resizable,
        closed: params.closed,
        cache: params.cache,
        closeAnimation: 'fade',
        closeDuration: 600,
        loadingMessage: '数据正在加载中，请稍后...',
        href: params.url,
        modal: params.modal,
        buttons: params.buttons,
        top: params.top,
        onClose: function () {
            $(this).dialog("destroy");
        }
    });

    var position = "hcenter";//params.position || "center";//vcenter,hcenter,center

    element.dialog(position);
}

/**
 * 关闭增删改查对话框
 * @param is_parent
 */
function closeCRUDDlg(is_parent, dlgId) {


    if (is_parent) {
        parent.$('#' + dlgId).dialog('destroy');
    } else {
        $('#' + dlgId).dialog('destroy');
    }
}


/**
 * 清空easyui表单
 * @param formId
 */
function clearForm(formId) {
    $('#' + formId).form('clear');
}

/**
 * 返回结果处理
 * @param dgId 数据表格的ID
 * @param data 返回的数据集合
 * @param close_dlg(true/false) 是否关闭对话框
 * @param is_parent(true/false) 对话框是否存在于父窗口
 */
function resultCallback(params) {

    if (params.is_parent == undefined) {
        params.is_parent = false;
    }

    if (typeof params.data != 'object') {
        params.data = eval('(' + params.data + ')');
    }

    if (params.close_dlg == undefined) {
        params.close_dlg = false;
    }

    if (params.isClose == undefined) {
        params.isClose = true;
    }

    if (params.elementType == undefined) {
        params.elementType = WIDGET_TYPE.DATAGRID;
    }

    if (params.dlgId === undefined) {
        params.dlgId = 'crud_dlg';
    }

    if (params.data.flag) {

        $.messager.alert("提示框", params.data.message, 'info', function () {
            if (params.isClose) {
                closeCRUDDlg(params.is_parent, params.dlgId);//关闭弹出窗口
            }

            if (params.elementType == WIDGET_TYPE.DATAGRID) {
                $("#" + params.element).datagrid("reload");
            } else if (params.elementType == WIDGET_TYPE.TREEGRID) {
                $("#" + params.element).treegrid("reload");
            } else if (params.elementType == WIDGET_TYPE.COMBOBOX) {
                $("#" + params.element).combobox("reload");
            } else if (params.elementType == WIDGET_TYPE.TREE) {
                $("#" + params.element).tree("reload");
            }
        });

    } else {
        $.messager.alert("警告框", params.data.message, 'warning');
    }
}

//时间格式化
Date.prototype.format = function (format) {
    if (!format) {
        format = "yyyy-MM-dd hh:mm:ss";
    }
    var o = {
        "M+": this.getMonth() + 1, // month
        "d+": this.getDate(), // day
        "h+": this.getHours(), // hour
        "m+": this.getMinutes(), // minute
        "s+": this.getSeconds(), // second
        "q+": Math.floor((this.getMonth() + 3) / 3), // quarter
        "S": this.getMilliseconds()
        // millisecond
    };
    if (/(y+)/.test(format)) {
        format = format.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    }
    for (var k in o) {
        if (new RegExp("(" + k + ")").test(format)) {
            format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length));
        }
    }
    return format;
};

function fomatDate(str) {
    return (new Date(parseInt(str.substring(str.indexOf('(') + 1, str.indexOf(')'))))).format("yyyy-MM-dd hh:mm:ss");
}


function showMsg(title, msg, isAlert) {
    if (isAlert !== undefined && isAlert) {
        $.messager.alert(title, msg);
    } else {
        $.messager.show({
            title: title,
            msg: msg,
            showType: 'show'
        });
    }
}


function showConfirm(title, msg, callback) {
    $.messager.confirm(title, msg, function (r) {
        if (r) {
            if (jQuery.isFunction(callback))
                callback.call();
        }
    });
}


function showProcess(isShow, title, msg) {
    if (!isShow) {
        $.messager.progress('close');
        return;
    }
    var win = $.messager.progress({
        title: title,
        msg: msg
    });
}

/**
 * 根据数据字典类型获取数据字典信息
 * @param dictId
 */
function getDictByType(dictId) {

    var url = contextRootPath + "/dict/findByDictId.action";
    var result = "";

    $.ajax({
        url: url,
        data: {"entity.dictId": dictId},
        async: false,
        success: function (data) {
            if (data) {
                result = eval('(' + data + ')');
            }
        }
    });

    return result;
}


function changeLanguage(lang) {
    $.cookie('_locale', lang, {expires: 30, path: '/'});
    top.location.reload();
}

function changeTenant(tenant) {
    $.cookie('tenantId', tenant, {expires: 30, path: '/'});
    top.location.reload();
}


/**
 * 检查Session是否已经过期
 * @returns {flag:true/false}
 */
function checkSesssionIsValid() {
    var result = {};
    $.ajax({
        url: contextRootPath + "/checkSessionIsValid",
        async: false,
        dataType: 'json',
        success: function (data) {
            result = data;
        }
    });

    if (!result.flag) {
        top.location.href = contextRootPath + "/user/login";
    }
}

var AUTH_TYPE = {
    "00": "指纹",
    "01": "虹膜",
    "02": "本地人脸",
    "10": "远程人脸",
    "11": "远程声纹",
    "12": "实名认证",
    "13": "人脸实名认证"
}

var STATISTICS_RESULT_KEY = {
    "FINGERPRINT": "00",
    "IRIS": "01",
    "LOCAL_FACE": "02",
    "GESTURE": "03",
    "REMOTE_FACE": "10",
    "REMOTE_VOICE": "11",
    "REMOTE_REAL_NAME": "12",
    "REMOTE_FACEANDREAL_NAME": "13",
    "SCAN_CODE": "14",
    "ALL": "statistics_all"
}

var STATISTICS_TYPE = {
    "STATISTICS_KEY_REGCOUNT": "regCount",
    "STATISTICS_KEY_REGCOMPARECOUNT": "regCompareCount",
    "STATISTICS_KEY_LOGOUTCOUNT": "logoutCount",
    "STATISTICS_KEY_LOGOUTCOMPARECOUNT": "logoutCompareCount",
    "STATISTICS_KEY_VERIFY": "verify"
}

var WIDGET_TYPE = {
    "DATAGRID": "datagrid",
    "TREEGRID": "treegrid",
    "COMBOBOX": "combobox",
    "TREE": "tree"
}

var OPER_TYPE = {
    "0": "用户状态查询",
    "1": "注册发起",
    "2": "注册完成",
    "3": "认证发起",
    "4": "认证完成",
    "5": "注销",
    "6": "注销所有",
    "7": "设备支持",
    "8": "设备查询",
    "9": "实名发起",
    "10": "实名完成"
}


var DATATYPE = {
    NUMBER: 'number',
    STRING: 'string',
    BOOLEAN: 'boolean'
}

var SYSTEM_CONST = {
    "SUPER_MANAGER_ID": "923a151cce714758b26acc31cd9ec212",
    "SYSTEM_CONFIG_MENU_ID": "49533ef0beb449c29b870bd018515d86"
}


$.ajaxSetup({
    type: 'POST',
    complete: function (xhr, status) {
        var sessionStatus = xhr.getResponseHeader('sessionstatus');
        if (sessionStatus === 'timeout') {
            var top = getTopWinow();
            $.messager.alert("提示", "由于您长时间没有操作, session已过期, 请重新登录.", 'info', function () {
                top.location.href = contextRootPath + '/user/login';
            });
        }
    }
});

function getTopWinow() {
    var p = window;
    while (p != p.parent) {
        p = p.parent;
    }
    return p;
}

function uuid() {
    var s = [];
    var hexDigits = "0123456789abcdef";
    for (var i = 0; i < 36; i++) {
        s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
    }
    s[14] = "4"; // bits 12-15 of the time_hi_and_version field to 0010
    s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1); // bits 6-7 of the clock_seq_hi_and_reserved to 01
    s[8] = s[13] = s[18] = s[23] = "";

    var uuid = s.join("");
    return uuid;
}


/**
 * 扩展树表格级联勾选方法：
 * @param {Object} container
 * @param {Object} options
 * @return {TypeName}
 */
$.extend($.fn.treegrid.methods, {
    /**
     * 级联选择
     * @param {Object} target
     * @param {Object} param
     *      param包括两个参数:
     *          id:勾选的节点ID
     *          deepCascade:是否深度级联
     * @return {TypeName}
     */
    cascadeCheck: function (target, param) {
        var opts = $.data(target[0], "treegrid").options;
        if (opts.singleSelect)
            return;
        var idField = opts.idField;//这里的idField其实就是API里方法的id参数
        var status = false;//用来标记当前节点的状态，true:勾选，false:未勾选
        var selectNodes = $(target).treegrid('getSelections');//获取当前选中项
        for (var i = 0; i < selectNodes.length; i++) {
            if (selectNodes[i][idField] == param.id)
                status = true;
        }
        //级联选择父节点
        selectParent(target[0], param.id, idField, status);
        selectChildren(target[0], param.id, idField, param.deepCascade, status);

        /**
         * 级联选择父节点
         * @param {Object} target
         * @param {Object} id 节点ID
         * @param {Object} status 节点状态，true:勾选，false:未勾选
         * @return {TypeName}
         */
        function selectParent(target, id, idField, status) {
            var parent = $(target).treegrid('getParent', id);
            if (parent) {
                var parentId = parent[idField];
                if (status)
                    $(target).treegrid('select', parentId);
                else
                    $(target).treegrid('unselect', parentId);
                selectParent(target, parentId, idField, status);
            }
        }

        /**
         * 级联选择子节点
         * @param {Object} target
         * @param {Object} id 节点ID
         * @param {Object} deepCascade 是否深度级联
         * @param {Object} status 节点状态，true:勾选，false:未勾选
         * @return {TypeName}
         */
        function selectChildren(target, id, idField, deepCascade, status) {
            //深度级联时先展开节点
            if (!status && deepCascade)
                $(target).treegrid('expand', id);
            //根据ID获取下层孩子节点
            var children = $(target).treegrid('getChildren', id);
            for (var i = 0; i < children.length; i++) {
                var childId = children[i][idField];
                if (status)
                    $(target).treegrid('select', childId);
                else
                    $(target).treegrid('unselect', childId);
                selectChildren(target, childId, idField, deepCascade, status);//递归选择子节点
            }
        }
    }
});